import { createSlice, PayloadAction } from "@reduxjs/toolkit"

export interface TabState {
  isCollapsed: boolean
  tagView: Array<TagView>
}

interface TagView {
  path: string
  name: string
  label: string
}

const tabSlice = createSlice({
  name: 'tab',
  initialState: {
    isCollapsed: false,
    tagView: [
      {
        path: '/home',
        name: 'home',
        label: '首页'
      }
    ]
  },
  reducers: {
    collapseMenu: (state: TabState, action: PayloadAction<boolean>) => {
      state.isCollapsed = action.payload
    },
    addTagView: (state: TabState, action: PayloadAction<TagView>) => {
      if (action.payload.name !== 'home') {
        // tagView 内不存在即添加进去
        if (!state.tagView.some(item => item.name === action.payload.name)) {
          state.tagView.push(action.payload)
        }
      }
    },
    removeTagView: (state: TabState, action: PayloadAction<TagView>) => {
      state.tagView = state.tagView.filter(item => item.name !== action.payload.name)
    }
  }
})

export const { collapseMenu, addTagView, removeTagView } = tabSlice.actions
export default tabSlice.reducer